//
//  YJNetworkTool.m
//  YJB
//
//  Created by 中电大维 on 16/5/14.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "YJNetworkTool.h"
#import "YJUserDefaultTool.h"
@interface YJNetworkTool()
@end

@implementation YJNetworkTool
+ (NSURLSessionDataTask *)postWithUrl:(NSString *)url parameters:(id)parameters success:(void (^)(id responseObject))success
    failure:(void (^)(NSError *error))failure
{

    NSURL *commomUrl = [NSURL URLWithString:url];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:commomUrl];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setValue:@"text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    req.timeoutInterval = 15.0f;
    req.HTTPMethod = @"POST";
    req.HTTPBody = [self stringWithDict:parameters];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error || data == nil)
            {
                if (failure)
                    failure(error);
            }
            else
            {
                if(success)
                {
                    NSString *dataString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                    dataString = [dataString urlDecode];
                    //手机处于停机情况下，若使用4G网络，返回的数据格式有误，当做失败处理
                    if (dataString == nil)
                    {
                        if (failure)
                            failure(nil);
                        return;
                    }
                    NSData *responseData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
                    success(dict);
                }
            }
        });
    }];
    //执行任务
    [task resume];
    return task;
}

+ (NSData *)stringWithDict:(NSDictionary *)dict
{
    NSData *dictData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *str = [[NSString alloc]initWithData:dictData encoding:NSUTF8StringEncoding];
    str = [str urlEncode];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}

#pragma mark ------------------ AFN网络二次封装
+ (NSURLSessionDataTask *)postWithUrl:(NSString *)url oringnParameters:(id)oringnParameters success:(void (^)(id responseObject))success
                              failure:(void (^)(NSError *error))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:10.0f];
    [manager.requestSerializer setValue:@"Mozilla/5.0" forHTTPHeaderField:@"User-Agent"  ];
    return [manager POST:url parameters:oringnParameters success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success)
        {
            NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            success(dict);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failure)
            failure(error);
    }];
}

+ (void)uploadWithUrl:(NSString *)url
           parameters:(id)parameters
        bodyWithBlock:(void (^)(id<AFMultipartFormData>formData))bodyWithBlock
             progress:(nullable void (^)(NSProgress * _Nonnull uploadProgress))progress
              success:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSDictionary *_Nonnull responseObject))success
              failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *_Nonnull error))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //发送的是JSON数据
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //接收的是数据流
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (bodyWithBlock) {
            bodyWithBlock(formData);
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress)
        {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if (success)
        {
            success(task,dict);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(task,error);
        }
    }];
}


@end
